package com.jic.market.exception;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.RestResult;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 参数不能为空 统一异常返回
 * @author wwb
 */
@ControllerAdvice
public class MethodNotNullExcepion {

    @ResponseStatus(value = HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public void handleArgumentNotValidException(MethodArgumentNotValidException e, HandlerMethod method, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset=UTF-8");
        resp.getWriter().write(JSONArray.toJSONString(RestResult.error("5000",e.getBindingResult().getFieldError().getDefaultMessage())));
    }
}
